package com.zyt.wiki.util;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class RateUtils {

    /**
     * 	获取请求方的IP地址
     * @param request
     */
    public static String getIP(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 若经过代理，会将代理地址拼在后面，如：IP0, IP1, IP2，第一个IP才是真实IP
        if(!StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            ip = ip.split(",")[0] ;
        }
        return ip;
    }

}
